/* eslint-disable react-hooks/rules-of-hooks */
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Select, DatePicker } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import router from 'umi/router';
import styles from './index.less';
import moment from 'moment';
import { _lostItemType, _customsSupervision, _lostItemStatus, _handoverDept } from '../lostItemInfoManage/components/_data'
import HandoverForm from './components/HandoverForm'

// 变量
let hiddenData = {
  flightDate: moment()
}

const { Option } = Select;

const LostItemHandover = () => {

  const actionRef = useRef();
  const ref = useRef()

  // 表格高度
  const [height, controlH] = useState(300)
  // 表格是否折叠
  const [isCollapse, controlC] = useState(true);
  // 交接弹窗显隐
  const [handoverVisible, handleHandoverVisible] = useState(false)
  // 保存搜索数据
  const [searchData, handleSearchData] = useState({})

  // 入库开始时间禁用
  const disabledStorageStartDate = (current) => {
    return ref.current.getFieldsValue().storageEndDate && current && moment(current).endOf('day') > ref.current.getFieldsValue().storageEndDate.endOf('day');
  }

  // 入库结束时间禁用
  const disabledStorageEndDate = (current) => {
    return ref.current.getFieldsValue().storageStartDate && current && moment(current).endOf('day') < ref.current.getFieldsValue().storageStartDate.endOf('day');
  }

  // 点击搜索
  const beforeSearchSubmit = params => {

    if (!params.storageStartDate) delete params.storageStartDate;
    if (!params.storageEndDate) delete params.storageEndDate;
    if (!params.flightDate) delete params.flightDate;

    if (!isCollapse) {
      handleSearchData(params)
      return params
    } else {
      if (event.target.querySelector('span').innerText === '搜 索') {
        if (Object.keys(params).indexOf('storageStartDate') === -1) {
          params.storageStartDate = ''
        }
        if (Object.keys(params).indexOf('storageEndDate') === -1) {
          params.storageEndDate = ''
        }
        handleSearchData({ ...hiddenData, ...params })
        return { ...hiddenData, ...params }
      } else if (event.target.querySelector('span').innerText === '重 置') {
        handleSearchData({})
        hiddenData = {}
        return params
      }
    }
  }

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 430);
    } else {
      controlH(document.body.clientHeight - 555);
    }
  }, [isCollapse])

  // 切换tab清空搜索
  useEffect(() => {
    hiddenData = {
      flightDate: moment()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const columns = [
    {
      title: '入库开始日期',
      dataIndex: 'storageStartDate',
      width: 200,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            disabledDate={disabledStorageStartDate}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '入库结束日期',
      dataIndex: 'storageEndDate',
      width: 200,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            disabledDate={disabledStorageEndDate}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '遗失物品编号',
      dataIndex: 'lostItemNumber',
      width: 140,
      // eslint-disable-next-line jsx-a11y/anchor-is-valid
      render: (text, _) => (<a onClick={() => {
        router.push('/banksearchSystem/lostItemManage/lostItemDetail')
      }}>{text}</a>),
      fixed: 'left',
      hideInSearch: true
    },
    {
      title: '遗失物品类别',
      dataIndex: 'lostItemType',
      width: 200,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _lostItemType && _lostItemType.length && _lostItemType.map((v, i) => {
                return (
                  <Option key={v.id}>{v.name}</Option>
                )
              })
            }
          </Select>
        );
      },
      render: (text, record) => (
        <span>
          {text === '0' ? '食品、药品、保健品、香烟、酒水等入口物品' : ''}
          {text === '1' ? '生活日用品、服装鞋帽、工艺品（含字画）' : ''}
          {text === '2' ? '书籍等无价值物品' : ''}
          {text === '3' ? '鲜活、易腐物品' : ''}
          {text === '4' ? '军用品、历史文物、珍贵图书类' : ''}
          {text === '5' ? '珠宝玉石、证件、银行卡等物品' : ''}
          {text === '6' ? '现金、有价票据、贵金属' : ''}
          {text === '7' ? '电子类、虫草类物品' : ''}
          {text === '8' ? '违禁物品' : ''}
          {text === '9' ? '贵重物品' : ''}
        </span>
      ),
      // ellipsis: true
    },
    {
      title: '遗失物品名称',
      dataIndex: 'lostItemName',
      width: 200,
      // eslint-disable-next-line jsx-a11y/anchor-is-valid
      render: (text, _) => (<a>{text}</a>),
      ellipsis: true
    },
    {
      title: '遗失物品特征',
      dataIndex: 'lostItemCharacter',
      width: 200,
      // eslint-disable-next-line jsx-a11y/anchor-is-valid
      render: (text, _) => (<a>{text}</a>),
      ellipsis: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNumber',
      width: 120
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
    },
    {
      title: '海关监督',
      dataIndex: 'customsSupervision',
      width: 200,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _customsSupervision && _customsSupervision.length && _customsSupervision.map((v, i) => {
                return (
                  <Option key={v.id}>{v.name}</Option>
                )
              })
            }
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '是否海关监督',
      dataIndex: 'isCustomsSupervision',
      width: 120,
      render: (text, record) => (
        <span>
          {text === '0' ? '是' : ''}
          {text === '1' ? '否' : ''}
        </span>
      ),
      hideInSearch: true
    },
    {
      title: '遗失物品状态',
      dataIndex: 'lostItemStatus',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _lostItemStatus && _lostItemStatus.length && _lostItemStatus.map((v, i) => {
                return (
                  <Option key={v.id}>{v.name}</Option>
                )
              })
            }
          </Select>
        );
      },
      render: (text, record) => (
        <span>
          {text === '0' ? '回收' : ''}
          {text === '1' ? '入库' : ''}
          {text === '2' ? '旅客领取' : ''}
          {text === '3' ? '报废' : ''}
          {text === '4' ? '移交' : ''}
          {text === '5' ? '交接' : ''}
        </span>
      ),
    },
    {
      title: '交接部门',
      dataIndex: 'handoverDept',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _handoverDept.map((v, i) => {
                return (
                  <Option key={v.id}>{v.name}</Option>
                )
              })
            }
          </Select>
        );
      },
      render: (text, record) => (
        <span>
          {text === '0' ? '清洁队' : ''}
          {text === '1' ? '服务室' : ''}
          {text === '2' ? '行李室' : ''}
          {text === '3' ? '国际客运室' : ''}
          {text === '4' ? '高端客户室' : ''}
          {text === '5' ? '值机室' : ''}
          {text === '6' ? '客舱服务部' : ''}
        </span>
      ),
    },
    {
      title: '是否结案',
      dataIndex: 'closingStatus',
      width: 120,
      render: (text, record) => (
        <span>
          {text === '0' ? '未结案' : ''}
          {text === '1' ? '已结案' : ''}
        </span>
      ),
      hideInSearch: true
    },
    {
      title: '入库人',
      dataIndex: 'storagePerson',
      width: 120,
      hideInSearch: true
    }
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="flightId"
        className={styles.lostItemHandover}
        headerTitle={
          <div>
            <span style={{ fontWeight: "700", color: "rgba(0,0,0,0.85)", fontSize: '16px' }}>遗失物品信息数据列表</span>
          </div>
        }
        options={{ fullScreen: true, reload:false, setting: true, density: false }}
        rowSelection={{}}
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          span: 6,
          onCollapse: val => {
            controlC(val)
            if (!val && hiddenData) {
              setTimeout(() => {
                ref.current.setFieldsValue({
                  lostItemName: hiddenData.lostItemName,
                  lostItemCharacter: hiddenData.lostItemCharacter,
                  flightNumber: hiddenData.flightNumber,
                  flightDate: hiddenData.flightDate,
                  customsSupervision: hiddenData.customsSupervision,
                  lostItemStatus: hiddenData.lostItemStatus,
                  handoverDept: hiddenData.handoverDept
                })
              }, 0)
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          },
          searchText: '搜索'
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => {
            handleHandoverVisible(true)
          }}>
            交接
          </Button>,
          <Button type="primary">
            导出Excel
          </Button>
        ]}
        tableAlertRender={false}
        request={(params) => {}}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 900, y: height }}
      />
      {
        handoverVisible && <HandoverForm
          onCancel={() => handleHandoverVisible(false)}
          handoverVisible={handoverVisible}
        ></HandoverForm>
      }
    </>
  );
};

export default Form.create()(LostItemHandover);
